package org.ykh.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.ykh.springcloud.entities.CommonResult;
import org.ykh.springcloud.entities.Payment;
import org.ykh.springcloud.service.PaymentService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ykh
 * @create 2022-01-03 18:59
 */
@RestController
@Slf4j
public class PaymentController {
    @Value("${server.port}")
    private String serverPort;

    @Autowired
    PaymentService paymentService;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        CommonResult commonResult;
        if (result > 0) {
            commonResult = new CommonResult(200, "成功 " + serverPort);
            log.info("插入{}成功" + payment);
        } else {
            commonResult = new CommonResult(400, "失败");
            log.info("{}插入失败", payment);
        }
        return commonResult;

    }

    @GetMapping("/payment/getPaymentById/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment result = paymentService.getPaymentById(id);
        CommonResult<Payment> commonResult;
        if (result != null) {
            commonResult = new CommonResult<Payment>(200, "成功 " + serverPort, result);
            log.info("{}查询成功", id);
        } else {
            commonResult = new CommonResult(400, "失败");
            log.info("{}查询失败", id);
        }
        return commonResult;
    }
    //服务发现
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        //服务
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }
        //CLOUD-PAYMENT-SERVICE服务的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
                    + element.getUri());
        }
        return this.discoveryClient;
    }

    //测试openFeign的超时控制
    @GetMapping("/payment/timeout")
    public CommonResult OpenFeignTimeout(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new CommonResult(200, "成功");
    }
}
